package cn.chiship.framework.upms.biz.system.controller;

import cn.chiship.framework.upms.biz.system.entity.UpmsQuartzJob;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsQuartzJobDto;
import cn.chiship.sdk.core.annotation.Authorization;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.util.ClassUtil;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;

import javax.annotation.Resource;
import javax.validation.Valid;

import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.pojo.vo.PageVo;
import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.common.quartz.CronTaskRegistrar;
import cn.chiship.framework.common.quartz.SchedulingRunnable;
import cn.chiship.framework.upms.biz.system.service.UpmsQuartzJobService;
import cn.chiship.framework.upms.biz.system.entity.UpmsQuartzJobExample;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 定时任务控制层 2021/12/2
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/quartzJob")
@Api(tags = "定时任务")
public class UpmsQuartzJobController extends BaseController<UpmsQuartzJob, UpmsQuartzJobExample> {

	private static final Logger LOGGER = LoggerFactory.getLogger(UpmsQuartzJobController.class);

	@Resource
	private UpmsQuartzJobService upmsQuartzJobService;

	@Resource
	private CronTaskRegistrar cronTaskRegistrar;

	@Override
	public BaseService getService() {
		return upmsQuartzJobService;
	}

	@SystemOptionAnnotation(describe = "定时任务分页查询")
	@ApiOperation(value = "定时任务分页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", dataTypeClass = Long.class,
					paramType = "query"),
			@ApiImplicitParam(name = "limit", value = "每页条数", defaultValue = "10", dataTypeClass = Long.class,
					paramType = "query"),
			@ApiImplicitParam(name = "sort", value = "排序方式", defaultValue = "-gmtModified",
					dataTypeClass = String.class, paramType = "query"),
			@ApiImplicitParam(name = "jobTitle", value = "任务名称", dataTypeClass = String.class, paramType = "query"),
			@ApiImplicitParam(name = "jobClass", value = "任务类名", dataTypeClass = String.class, paramType = "query")

	})
	@GetMapping(value = "/page")
	public ResponseEntity<BaseResult> page(
			@RequestParam(required = false, defaultValue = "", value = "jobTitle") String jobTitle,
			@RequestParam(required = false, defaultValue = "", value = "jobClass") String jobClass) {
		UpmsQuartzJobExample upmsQuartzJobExample = new UpmsQuartzJobExample();
		// 创造条件
		UpmsQuartzJobExample.Criteria criteria = upmsQuartzJobExample.createCriteria();
		if (!StringUtil.isNullOrEmpty(jobTitle)) {
			criteria.andJobTitleLike("%" + jobTitle + "%");
		}
		if (!StringUtil.isNullOrEmpty(jobClass)) {
			criteria.andJobClassLike("%" + jobClass + "%");
		}

		PageVo pageVo = super.page(upmsQuartzJobExample);
		return super.responseEntity(BaseResult.ok(pageVo));
	}

	@SystemOptionAnnotation(describe = "保存定时任务", option = BusinessTypeEnum.SYSTEM_OPTION_SAVE)
	@ApiOperation(value = "保存定时任务")
	@PostMapping(value = "save")
	public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsQuartzJobDto upmsQuartzJobDto) {
		UpmsQuartzJob upmsQuartzJob = new UpmsQuartzJob();
		BeanUtils.copyProperties(upmsQuartzJobDto, upmsQuartzJob);
		BaseResult baseResult = super.save(upmsQuartzJob);
		if (baseResult.isSuccess()) {
			SchedulingRunnable task = new SchedulingRunnable(upmsQuartzJob.getJobClass(), upmsQuartzJob.getJobMethod(),
					upmsQuartzJob.getJobParam());
			cronTaskRegistrar.addCronTask(task, upmsQuartzJob.getJobCron());
		}

		return super.responseEntity(baseResult);
	}

	@SystemOptionAnnotation(describe = "更新定时任务", option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE)
	@ApiOperation(value = "更新定时任务")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"), })
	@PostMapping(value = "update/{id}")
	public ResponseEntity<BaseResult> update(@PathVariable("id") String id,
			@RequestBody @Valid UpmsQuartzJobDto upmsQuartzJobDto) {
		UpmsQuartzJob upmsQuartzJob = new UpmsQuartzJob();
		BeanUtils.copyProperties(upmsQuartzJobDto, upmsQuartzJob);
		BaseResult baseResult = super.update(id, upmsQuartzJob);
		if (baseResult.isSuccess()) {
			// 先移除再添加
			UpmsQuartzJob quartzJob = upmsQuartzJobService.selectByPrimaryKey(id);
			SchedulingRunnable task = new SchedulingRunnable(quartzJob.getJobClass(), quartzJob.getJobMethod(),
					quartzJob.getJobParam());
			cronTaskRegistrar.removeCronTask(task);

			task = new SchedulingRunnable(upmsQuartzJob.getJobClass(), upmsQuartzJob.getJobMethod(),
					upmsQuartzJob.getJobParam());
			cronTaskRegistrar.addCronTask(task, upmsQuartzJob.getJobCron());

		}
		return super.responseEntity(baseResult);
	}

	@SystemOptionAnnotation(describe = "删除定时任务", option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE)
	@ApiOperation(value = "删除定时任务")
	@PostMapping(value = "remove")
	public ResponseEntity<BaseResult> remove(@RequestBody List<String> ids) {
		UpmsQuartzJobExample upmsQuartzJobExample = new UpmsQuartzJobExample();
		upmsQuartzJobExample.createCriteria().andIdIn(ids);
		List<UpmsQuartzJob> quartzJobs = upmsQuartzJobService.selectByExample(upmsQuartzJobExample);

		BaseResult baseResult = super.remove(upmsQuartzJobExample);

		if (baseResult.isSuccess()) {
			for (UpmsQuartzJob quartzJob : quartzJobs) {
				SchedulingRunnable task = new SchedulingRunnable(quartzJob.getJobClass(), quartzJob.getJobMethod(),
						quartzJob.getJobParam());
				cronTaskRegistrar.removeCronTask(task);
			}
		}

		return super.responseEntity(baseResult);
	}

	@ApiOperation(value = "定时任务启用(true)、停止(false)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"), })
	@PostMapping(value = "changeIsState/{id}")
	public ResponseEntity<BaseResult> changeIsState(@PathVariable("id") String id, @RequestBody @Valid Boolean status) {
		UpmsQuartzJob quartzJob = upmsQuartzJobService.selectByPrimaryKey(id);

		quartzJob.setStatus(Boolean.FALSE.equals(status) ? BaseConstants.YES : BaseConstants.NO);
		BaseResult baseResult = upmsQuartzJobService.updateByPrimaryKeySelective(quartzJob);
		if (baseResult.isSuccess()) {
			SchedulingRunnable task = new SchedulingRunnable(quartzJob.getJobClass(), quartzJob.getJobMethod(),
					quartzJob.getJobParam());
			cronTaskRegistrar.removeCronTask(task);
			if (Boolean.TRUE.equals(status)) {
				task = new SchedulingRunnable(quartzJob.getJobClass(), quartzJob.getJobMethod(),
						quartzJob.getJobParam());
				cronTaskRegistrar.addCronTask(task, quartzJob.getJobCron());
			}

		}
		return super.responseEntity(baseResult);
	}

	@ApiOperation(value = "获得所有任务名称及方法名称")
	@GetMapping(value = "/getTaskNameAndMethodNames")
	public ResponseEntity<BaseResult> getTaskNameAndMethodNames() {
		return super.responseEntity(BaseResult.ok(ClassUtil.getClassList("cn.chiship.framework.business.core.task")));
	}

}